package pcp

import (
	"encoding/base64"
	"gitee.com/teval/uts"
	"github.com/forgoer/openssl"
)

// DesECBEncrypt DesECB加密
//
// 注意：key、iv都是固定长度：64bit，即8个字符（UTF-8）
func DesECBEncrypt(value, key string, pad ...string) (string, error) {
	var p = openssl.PKCS5_PADDING
	if len(pad) > 0 {
		p = uts.Nvl(pad[0], p)
	}
	a := NewDesECBCrypt(key, p)
	return a.Encrypt([]byte(value))
}

func DesECBDecrypt(value, key string, pad ...string) (string, error) {
	var p = openssl.PKCS5_PADDING
	if len(pad) > 0 {
		p = uts.Nvl(pad[0], p)
	}
	a := NewDesECBCrypt(key, p)
	return a.Decrypt(value)
}

func NewDesECBCrypt(key string, pad ...string) (crypt *DesECBCrypt) {
	crypt = &DesECBCrypt{
		Key:     []byte(key),
		Padding: openssl.PKCS5_PADDING,
	}

	if len(pad) > 0 {
		crypt.Padding = pad[0]
	}

	return
}

type DesECBCrypt struct {
	Key     []byte
	Padding string
}

func (a *DesECBCrypt) Encrypt(src []byte) (rst string, err error) {
	dst, err := openssl.DesECBEncrypt(src, a.Key, a.Padding)
	if err != nil {
		return
	}
	rst = base64.StdEncoding.EncodeToString(dst)
	return
}

func (a *DesECBCrypt) Decrypt(data string) (rst string, err error) {
	src, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		return
	}
	dst, err := openssl.DesECBDecrypt(src, a.Key, a.Padding)
	if err != nil {
		return
	}
	rst = string(dst)
	return
}
